package format

import (
	"strings"

	"github.com/bluenviron/gortsplib/v4/pkg/format"
)

type (
	Format = format.Format
)

type (
	AV1        = format.AV1
	H264       = format.H264
	H265       = format.H265
	VP8        = format.VP8
	VP9        = format.VP9
	MPEG4Video = format.MPEG4Video
	MPEG1Video = format.MPEG1Video
	MJPEG      = format.MJPEG
	MPEGTS     = format.MPEGTS

	Opus       = format.Opus
	Vorbis     = format.Vorbis
	MPEG4Audio = format.MPEG4Audio
	MPEG1Audio = format.MPEG1Audio
	AC3        = format.AC3
	Speex      = format.Speex
	G726       = format.G726
	G722       = format.G722
	G711       = format.G711
	LPCM       = format.LPCM
	Generic    = format.Generic
)

func Unmarshal(mediaType string, payloadType uint8, rtpMap string, fmtp map[string]string) (Format, error) {
	f, err := format.Unmarshal(mediaType, payloadType, rtpMap, fmtp)
	if err != nil {
		return nil, err
	}

	switch f := f.(type) {
	case *AV1:
		_ = f.PayloadTyp
	case *H264:
	case *H265:
	case *VP8:
	case *VP9:
	case *MPEG4Video:
	case *MPEG1Video:
	case *MJPEG:
	case *MPEGTS:

	case *Opus:
	case *Vorbis:
	case *MPEG4Audio:
	case *MPEG1Audio:
	case *AC3:
	case *Speex:
	case *G726:
	case *G722:
	case *G711:
	case *LPCM:
	case *Generic:
		codecId := getCodec(f.RTPMa)
		switch codecId {
		case "MP2P":
			var ps = NewPS(*f)
			_ = ps.PayloadTyp

			return ps, nil
		}
	}

	return f, nil
}

func getCodec(rtpMap string) string {
	parts2 := strings.SplitN(rtpMap, "/", 2)
	if len(parts2) != 2 {
		return ""
	}

	return strings.ToUpper(parts2[0])
}
